#!/bin/bash

# 启动Spring Boot应用脚本
echo "🚀 启动Spring Boot应用..."

# 检查端口是否被占用
if lsof -i:8081 >/dev/null 2>&1; then
    echo "❌ 错误: 端口8081已被占用"
    echo "请先运行 ./stop.sh 停止现有进程"
    exit 1
fi

# 检查Maven路径
MAVEN_PATH="/Users/shafei/Desktop/bgyfw-tcpt/maven/apache-maven-3.6.1-tcpt/bin/mvn"
if [ ! -f "$MAVEN_PATH" ]; then
    echo "❌ 错误: Maven路径不存在: $MAVEN_PATH"
    exit 1
fi

# 启动应用
echo "   使用Maven启动应用..."
nohup "$MAVEN_PATH" spring-boot:run > app.log 2>&1 &
MAVEN_PID=$!

echo "   Maven进程PID: $MAVEN_PID"
echo "   日志文件: app.log"
echo ""

# 等待应用启动
echo "⏳ 等待应用启动..."
for i in {1..30}; do
    if curl -s http://localhost:8081/api/monitor/machines >/dev/null 2>&1; then
        echo "✅ 应用启动成功!"
        echo ""
        echo "📊 应用信息:"
        echo "   URL: http://localhost:8081"
        echo "   机器API: http://localhost:8081/api/monitor/machines"
        echo "   计划API: http://localhost:8081/api/monitor/pending-plans"
        echo ""
        
        # 显示机器数量
        MACHINE_COUNT=$(curl -s http://localhost:8081/api/monitor/machines | jq length 2>/dev/null || echo "未知")
        echo "   机器数量: $MACHINE_COUNT"
        exit 0
    fi
    
    echo "   等待中... ($i/30)"
    sleep 2
done

echo "❌ 错误: 应用启动超时"
echo "请检查日志文件: app.log"
exit 1 